import { Provide, Inject } from '@midwayjs/core'
import { Repository, In } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { Users } from '../../entities/Users.entity'
import { Certificate } from '../../entities/Certificate.entity'
import { encryptPassword } from '../../utils/cryptoUtils'

@Provide()
export class UserService {
  @InjectEntityModel(Users)
  repo!: Repository<Users>

  @InjectEntityModel(Certificate)
  certificateRepo!: Repository<Certificate>

  // 修改用户信息
  async updateProfile(userId: string, data: {
    nickname?: string
    email?: string
    signature?: string
    password?: string
    avatar?: string
  }) {
    // 查找用户
    const user = await this.repo.findOne({
      where: { id: userId }
    })

    if (!user) {
      throw new Error('用户不存在')
    }

    // 检查用户是否被禁用
    if (user.isDisabled) {
      throw new Error('该账号已被禁用')
    }

    // 如果要修改邮箱，检查邮箱是否已被其他用户使用
    if (data.email && data.email !== user.email) {
      const existEmail = await this.repo.findOne({
        where: { email: data.email }
      })
      if (existEmail && existEmail.id !== userId) {
        throw new Error('该邮箱已被其他用户使用')
      }
    }

    // 准备更新数据
    const updateData: Partial<Users> = {}
    
    if (data.nickname !== undefined) {
      updateData.nickname = data.nickname
    }
    
    if (data.email !== undefined) {
      updateData.email = data.email
    }
    
    if (data.signature !== undefined) {
      updateData.userSign = data.signature
    }

    if (data.avatar !== undefined) {
      updateData.avatar = data.avatar
    }
    
    if (data.password !== undefined && data.password !== '') {
      updateData.password = await encryptPassword(data.password)
    }

    // 更新用户信息
    await this.repo.update(userId, updateData)
  }

  // 获取用户信息
  async getUserInfo(userId: string) {
    const user = await this.repo.findOne({
      where: { id: userId }
    })

    if (!user) {
      throw new Error('用户不存在')
    }

    // 返回用户信息（不包含密码）
    const { password, ...userInfo } = user
    return userInfo
  }

  // 根据用户ID获取证书详情列表
  async getUserCertificates(userId: string) {
    // 查找用户
    const user = await this.repo.findOne({
      where: { id: userId }
    })

    if (!user) {
      throw new Error('用户不存在')
    }

    // 如果用户没有证书类型，返回空数组
    if (!user.certificateTypes) {
      return []
    }

    // 解析证书类型（逗号分隔的字符串）
    const types = user.certificateTypes.split(',').map(t => parseInt(t.trim())).filter(t => !isNaN(t))

    if (types.length === 0) {
      return []
    }

    // 查询匹配的证书详情
    const certificates = await this.certificateRepo.find({
      where: {
        type: In(types) as any
      }
    })

    return {
      items: certificates,
      total: certificates.length
    }
  }
}